import 'package:core/core.dart';

/// 基于list 带缓存逻辑
abstract class ViewStateListCacheModel<T> extends ViewStateListModel<T>
    with CacheData {
  final String listDataKey = 'listData';

  setListData(List<T> listData) {
    list = listData;
  }

  //初始化缓存数据  只处理list部分 其余的再各个页面处理
  dynamic initCacheData({String? key}) {
    try {
      var cacheData = getCacheData();
      if (cacheData != null) {
        setCached();
        if (key != null) {
          var keyCacheData = cacheData[key];
          if (keyCacheData != null && keyCacheData is List)
            list = handleData(keyCacheData);
        } else if (cacheData is List) {
          list = handleData(cacheData);
        }
      }
      return cacheData;
    } catch (e) {
      deleteCacheData();
    }
  }

  // 下拉刷新
  @override
  refresh({bool init = false}) async {
    try {
      List<T> data = await loadData();
      if (data.isEmpty) {
        list.clear();
        setEmpty();
      } else {
        list.clear();
        list.addAll(data);
        setIdle();
      }
      onCompleted(data);
    } catch (e, s) {
      if (list.isEmpty) {
        setError(e, s);
        onError(e, s);
        return null;
      } else {
        printErrorStack(e, s);
      }
      return list;
    }
  }

  onError(e, s) {}

  //子类重写 判断页面是否是empty状态 不只根据list去判断
  bool pageEmpty() {
    return list.isEmpty;
  }

  List<T> handleData(List listData) {
    return [];
  }
}
